-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[

]]--
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 
    local BATTERY_COST = 10  -- 每次转换电池消耗
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local assets =
{
    Asset("ANIM", "anim/loramia_building_esoteric_creation.zip"),
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 积雪
    local function snow_init(inst)
        if TheWorld.state.issnowcovered then
            -- inst.AnimState:Show("SNOW")
            inst.AnimState:ShowSymbol("snow")
        else
            -- inst.AnimState:Hide("SNOW")
            inst.AnimState:HideSymbol("snow")
        end    
    end
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 天赋
    local function IsPlayerTalentUnlocked(doer)
        if doer and doer.replica.loramia_com_talent_tree and doer.replica.loramia_com_talent_tree:IsUnlocked("evolution_subtlety") then
            return true
        end
        return false
    end
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- workable
    local function OnFinishCallback(inst,worker)
        inst.components.lootdropper:SpawnLootPrefab("loramia_item_alloy_circuit_board")
        inst.components.lootdropper:SpawnLootPrefab("loramia_item_alloy_circuit_board")
        inst.components.lootdropper:SpawnLootPrefab("loramia_item_luminous_alloy_board")
        local fx = SpawnPrefab("collapse_small")
        fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
        inst:Remove()
    end
    local function workable_install(inst)
        inst:AddComponent("workable")
        inst.components.workable:SetWorkAction(ACTIONS.DIG)
        inst.components.workable:SetWorkLeft(1)
        -- inst.components.workable:SetOnWorkCallback(onhit)
        inst.components.workable:SetOnFinishCallback(OnFinishCallback)
        local old_WorkedBy = inst.components.workable.WorkedBy
        inst.components.workable.WorkedBy = function(self,worker, numworks,...)
            if worker and worker:HasTag("player") then
                return old_WorkedBy(self,worker, numworks,...)
            end
        end
        local old_WorkedBy_Internal = inst.components.workable.WorkedBy_Internal
        inst.components.workable.WorkedBy_Internal = function(self,worker, numworks,...)
            if worker and worker:HasTag("player") then
                return old_WorkedBy_Internal(self,worker, numworks,...)
            end
        end
    end
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- acceptable    
    local function GetItemStackNum(item)
        if item.components.stackable then
            return item.components.stackable:StackSize()
        else
            return 1
        end
    end
    -- local function IsFruitOrVeggie(item) --- 蔬菜和水果
    --     local cooking = require("cooking")
    --     local ingredients = cooking.ingredients
    --     local data = ingredients[item.prefab]
    --     if type(data) == "table" then
    --         local tags = data.tags or {}
    --         if tags and (tags["fruit"] or tags["veggie"]) then
    --             return true
    --         end
    --     end
    --     return false
    -- end
    --------------------------------------------------------------------------------------------------------
    --- 种子植物对应
        local temp_Fruit_Veggie_List = {
            ["asparagus"] = "asparagus_seeds",                      --- 芦笋种子
            ["carrot"] = "carrot_seeds",                            --- 胡萝卜种子
            ["corn"] = "corn_seeds",                                --- 玉米种子
            ["eggplant"] = "eggplant_seeds",                        --- 茄子种子
            ["garlic"] = "garlic_seeds",                            --- 大蒜种子
            ["onion"] = "onion_seeds",                              --- 洋葱种子
            ["pepper"] = "pepper_seeds",                            --- 辣椒种子
            ["potato"] = "potato_seeds",                            --- 土豆种子
            ["pumpkin"] = "pumpkin_seeds",                          --- 南瓜种子
            ["tomato"] = "tomato_seeds",                            --- 番茄种子
            ["dragonfruit"] = "dragonfruit_seeds",                  --- 火龙果种子
            ["durian"] = "durian_seeds",                            --- 榴莲种子
            ["pomegranate"] = "pomegranate_seeds",                  --- 石榴种子
            ["watermelon"] = "watermelon_seeds",                    --- 西瓜种子
        }
        local Fruit_Veggie_2_Seed_List = {}
        for origin_prefab,seed_name in pairs(temp_Fruit_Veggie_List) do
            Fruit_Veggie_2_Seed_List[origin_prefab] = seed_name
            Fruit_Veggie_2_Seed_List[origin_prefab.."_cooked"] = seed_name
            Fruit_Veggie_2_Seed_List[origin_prefab.."_dried"] = seed_name
        end
    --------------------------------------------------------------------------------------------------------
    --- 肉类
        local function IsMeat(item)
            local cooking = require("cooking")
            local ingredients = cooking.ingredients
            local data = ingredients[item.prefab]
            if type(data) == "table" then
                local tags = data.tags or {}
                if tags["meat"] or tags["fish"] then
                    return true
                end
            end
            return false
        end
    --------------------------------------------------------------------------------------------------------
    --- 糖类
        local function IsSweetener(item)
            local cooking = require("cooking")
            local ingredients = cooking.ingredients
            local data = ingredients[item.prefab]
            if type(data) == "table" then
                local tags = data.tags or {}
                if tags["sweetener"]  then
                    return true
                end
            end
            return false
        end
    --------------------------------------------------------------------------------------------------------
    local function acceptable_install(inst)
        inst:ListenForEvent("Loramia_OnEntityReplicated.loramia_com_acceptable",function(inst,replica_com)
            replica_com:SetText("loramia_building_primordial_creation",STRINGS.ACTIONS.GIVE.GENERIC)
            replica_com:SetSGAction("give")
            replica_com:SetTestFn(function(inst,item,doer,right_click)
                return true
            end)
        end)
        if not TheWorld.ismastersim then
            return
        end

        inst:AddComponent("loramia_com_acceptable")
        inst.components.loramia_com_acceptable:SetOnAcceptFn(function(inst,item,doer)

            if not inst.components.loramia_com_power_device:CanTakePower(BATTERY_COST) then
                return false
            end
            ---------------------------------------------------------------------------
            --- 
                local item_num = GetItemStackNum(item)
                local battery_trans_cost_succeed = false
            ---------------------------------------------------------------------------
            ---  花草切换
                local cutgrass_switch_list = {
                    ["petals"] = true,              --- 花瓣
                    ["petals_evil"] = true,         --- 恶魔花瓣
                    ["succulent_picked"] = true,    --- 蕨菜
                    ["foliage"] = true,             --- 多肉
                }
                if cutgrass_switch_list[item.prefab] then
                    TUNING.LORAMIA_FN:GiveItemByName(doer,"cutgrass",item_num)
                    inst:PushEvent("play_ring_sound")
                    item:Remove()
                    battery_trans_cost_succeed = true
                    -- return true
                end
            ---------------------------------------------------------------------------
            --- 种子切换
                if Fruit_Veggie_2_Seed_List[item.prefab] then
                    TUNING.LORAMIA_FN:GiveItemByName(doer,Fruit_Veggie_2_Seed_List[item.prefab],item_num)
                    TUNING.LORAMIA_FN:GiveItemByName(doer,"compost",item_num)
                    inst:PushEvent("play_ring_sound")
                    item:Remove()
                    battery_trans_cost_succeed = true
                    -- return true
                end
            ---------------------------------------------------------------------------
            --- 肉类切换
                if IsMeat(item) then
                    TUNING.LORAMIA_FN:GiveItemByName(doer,"spoiled_food",item_num)
                    TUNING.LORAMIA_FN:GiveItemByName(doer,"boneshard",item_num)
                    inst:PushEvent("play_ring_sound")
                    item:Remove()
                    battery_trans_cost_succeed = true
                    -- return true
                end
            ---------------------------------------------------------------------------
            --- 糖类
                if IsSweetener(item) then
                    TUNING.LORAMIA_FN:GiveItemByName(doer,"ice",item_num)
                    inst:PushEvent("play_ring_sound")
                    item:Remove()
                    battery_trans_cost_succeed = true
                    -- return true
                end
            ---------------------------------------------------------------------------
            --- 荧光果、发光浆果
                local light_fruit_list = {
                    ["wormlight"] = true,
                    ["wormlight_lesser"] = true,
                    ["lightbulb"] = true,
                }
                if light_fruit_list[item.prefab] then
                    TUNING.LORAMIA_FN:GiveItemByName(doer,"loramia_item_luminescent_crystal",item_num)
                    inst:PushEvent("play_ring_sound")
                    item:Remove()
                    battery_trans_cost_succeed = true
                    -- return true
                end
            ---------------------------------------------------------------------------
            --- 天赋转换：
                if IsPlayerTalentUnlocked(doer) then
                    local trans_list = {
                        ["log"] = {"boards",1},
                        ["rocks"] = {"cutstone",1},
                        ["boards"] = {"turf_woodfloor",4},
                        ["cutstone"] = {"turf_road",4},
                    }
                    if trans_list[item.prefab] then
                        local stack_num = GetItemStackNum(item)
                        local ret_prefab = trans_list[item.prefab][1]
                        local ret_num = (trans_list[item.prefab][2] or 1)*stack_num
                        TUNING.LORAMIA_FN:GiveItemByName(doer,ret_prefab,ret_num)
                        inst:PushEvent("play_ring_sound")
                        item:Remove()
                        battery_trans_cost_succeed = true
                        -- return true
                    end
                end
            ---------------------------------------------------------------------------
            --- 
                if battery_trans_cost_succeed then
                    inst.components.loramia_com_power_device:IsGotPowerSucceed(BATTERY_COST)
                    return true
                end
            ---------------------------------------------------------------------------
            return false
        end)
    end
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- custom workable
    local function custom_workable_install(inst)
        inst:ListenForEvent("Loramia_OnEntityReplicated.loramia_com_workable",function(inst,replica_com)
            replica_com:SetTestFn(function(inst,doer,right_click)
                if right_click and (IsPlayerTalentUnlocked(doer) or TUNING.LORAMIA_DEBUGGING_MODE) then
                    return true
                end
            end)
            replica_com:SetText("loramia_building_mysterious_creation",STRINGS.ACTIONS.WRAPBUNDLE)
        end)
        if not TheWorld.ismastersim then
            return
        end
        inst:AddComponent("loramia_com_workable")
        inst.components.loramia_com_workable:SetActiveFn(function(inst,doer)
            local item = SpawnPrefab("loramia_building_esoteric_creation_kit")
            item.Transform:SetPosition(inst.Transform:GetWorldPosition())
            inst:Remove()
            return true
        end)
    end
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 动画控制
    local function anim_init(inst)
        inst.AnimState:HideSymbol("lines")
    end
    local function anim_update(inst)
        if inst.components.loramia_com_power_device and inst.components.loramia_com_power_device:CanTakePower(BATTERY_COST) then
            inst.AnimState:ShowSymbol("lines")
        else
            inst.AnimState:HideSymbol("lines")
        end
    end
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddLight()
    inst.entity:AddSoundEmitter()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddNetwork()

    MakeObstaclePhysics(inst, 1)


    -- inst.MiniMapEntity:SetIcon("loramia_building_esoteric_creation.tex")

    -- inst.AnimState:SetBank("loramia_building_esoteric_creation")
    -- inst.AnimState:SetBuild("loramia_building_esoteric_creation")
    -- inst.AnimState:PlayAnimation("idle",true)

    inst.AnimState:SetBank("loramia_building_esoteric_creation")
    inst.AnimState:SetBuild("loramia_building_esoteric_creation")
    inst.AnimState:PlayAnimation("idle",true)

    inst:AddTag("structure")
    inst:AddTag("loramia_building_esoteric_creation")

    -----------------------------------------------------------
    --- acceptable
        acceptable_install(inst)
    -----------------------------------------------------------
    --- 
        custom_workable_install(inst)
    -----------------------------------------------------------
    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end


    -----------------------------------------------------------
    --- 
        inst:DoPeriodicTask(1,anim_update)
    -----------------------------------------------------------
    --- 
        inst:ListenForEvent("play_ring_sound",function()
            inst.SoundEmitter:PlaySound("dontstarve/common/together/celestial_orb/active")
        end)        
    -----------------------------------------------------------
    --- 
        inst:AddComponent("inspectable")
    -----------------------------------------------------------
    --- 
        inst:AddComponent("lootdropper")
    -----------------------------------------------------------
    --- 官方的workable
        workable_install(inst)
    -----------------------------------------------------------
    --- 
        inst:AddComponent("loramia_com_power_device")
    -----------------------------------------------------------

    MakeHauntableLaunch(inst)

    return inst
end

----------------------------------------------------------------------------------------------------------------------
--- item
    local function item_fn()
        local inst = CreateEntity()
        inst.entity:AddTransform()
        inst.entity:AddAnimState()
        inst.entity:AddSoundEmitter()
        inst.entity:AddMiniMapEntity()
        inst.entity:AddNetwork()
        MakeInventoryPhysics(inst)
        MakeInventoryFloatable(inst, "med", 0.05, {0.85, 0.45, 0.85})
        inst.AnimState:SetBank("loramia_building_esoteric_creation")
        inst.AnimState:SetBuild("loramia_building_esoteric_creation")
        inst.AnimState:PlayAnimation("item")
        inst:AddTag("deploykititem")
        inst.entity:SetPristine()
        if not TheWorld.ismastersim then
            return inst
        end
        --------------------------------------------------------------------------
        ---
            inst:AddComponent("loramia_data")
        --------------------------------------------------------------------------
        ------ 物品名 和检查文本
            inst:AddComponent("inspectable")
            inst:AddComponent("inventoryitem")
            -- inst.components.inventoryitem:ChangeImageName("cane")
            inst.components.inventoryitem.imagename = "loramia_building_esoteric_creation_kit"
            inst.components.inventoryitem.atlasname = "images/inventoryimages/loramia_building_esoteric_creation_kit.xml"
        -------------------------------------------------------------------
            MakeHauntableLaunch(inst)
        -------------------------------------------------------------------
        --- 落水影子
            local function shadow_init(inst)
                if inst:IsOnOcean(false) then       --- 如果在海里（不包括船）
                    inst.AnimState:Hide("SHADOW")
                    -- inst.AnimState:HideSymbol("shadow")
                else                                
                    inst.AnimState:Show("SHADOW")
                    -- inst.AnimState:ShowSymbol("shadow")
                end
            end
            inst:ListenForEvent("on_landed",shadow_init)
            shadow_init(inst)
        -------------------------------------------------------------------
        --- 积雪
            inst:WatchWorldState("issnowcovered", snow_init)
            snow_init(inst)
        -------------------------------------------------------------------
        --- 放置
            inst:AddComponent("deployable")
            inst.components.deployable.ondeploy = function(inst,pt,player)
                local ret_inst = SpawnPrefab("loramia_building_esoteric_creation")
                ret_inst.Transform:SetPosition(pt.x,0,pt.z)
                inst:Remove()
            end
            inst.components.deployable:SetDeploySpacing(DEPLOYSPACING.NONE)
            inst.components.deployable.restrictedtag = "loramia"
        -------------------------------------------------------------------
        --- 特效
        -------------------------------------------------------------------
        return inst
    end
----------------------------------------------------------------------------------------------------------------------
--- placer    
    local function placer_postinit_fn(inst)
        TheWorld:PushEvent("loramia_com_power_battery_indicator_active",inst)
        anim_init(inst)
    end
----------------------------------------------------------------------------------------------------------------------

return Prefab("loramia_building_esoteric_creation", fn, assets),
    Prefab("loramia_building_esoteric_creation_kit", item_fn, assets),
    MakePlacer("loramia_building_esoteric_creation_kit_placer", "loramia_building_esoteric_creation", "loramia_building_esoteric_creation", "idle", nil, nil, nil, nil, nil, nil, placer_postinit_fn)


